<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('hardwareOut.hardwareDelivery')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('hardwareOut.barcodeInformation') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('hardwareOut.materialsDepartment') }}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.peportmentList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text"
							v-model="data.department" @select="departmentSelect"></superweiCombox>
					</view>
					<!-- <view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('materials.expenseItem') }}：</text>
						<comboGrid ref="comboGridRef" v-model="data.costItem" :requestParam="data.requestParam"
							requestUrl="/api1/wms/getValueSet/GetDicItemByCode" :calculate='false'
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="value"
							:column="data.columnRule.column" bindValue="value" @setClick="chooseSelectCostItem">
						</comboGrid>
					</view> -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('materials.remark') }}：</text>
						<input type="text" v-model="data.remark" class="gui-form-input gui-text-right"
							:placeholder="$t('materials.pleaseRemarks')" />
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"
							style="padding-right: 40rpx;">{{ $t('hardwareOut.scanMaterialCard') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" type="search"
							:placeholder="$t('hardwareOut.pleaseScanMaterial')" @confirm="confirm"
							@iconClick="iconClick"></uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0">
						<text class="item-info-title" style="padding-right: 40rpx"><text class="required-color"
								style="padding-right: 6rpx">*</text>{{ $t('hardwareOut.outQty') }}：</text>
						<uni-easyinput disabled class="uni-mt-5" type="number" v-model="data.allInputNum">
						</uni-easyinput>
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view class="custom-form-card">
					<uni-collapse v-if="data.scanInfo" v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content" style="margin-top: 10rpx;">
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
												data.scanInfo.materialCode
										}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
												data.scanInfo.materialName
										}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
											data.scanInfo.materialSpec || ''
									}}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{
												data.scanInfo.currentQty
										}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
												data.scanInfo.unit
										}}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">
						{{ $t('hardwareOut.hardwareGenerate') }}</view>
				</view>
			</view>
			<!-- 弹框填写数量 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.materialName }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.uom') }}:{{ data.scanInfo.unit }}
						</view>
						<view class="input-dialog-item">
							{{ $t('JsInternational.ofStock') }}:{{ data.scanInfo.currentQty }}
						</view>
						<view class="gui-form-item" style="color: #dd524d">
							<text style="width:210rpx;">{{ $t('hardwareOut.outQty') }}：</text>
							<view>
								<input type="number" style="margin: 8rpx 0;" class="gui-form-input"
									v-model="data.scanInfo.inputNum" :placeholder="$t('materials.pleaseEnterThe')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import superweiCombox from '@/components/superweiCombox';
import comboGrid from '@/components/comboGrid.vue'
import chooseSelect from '@/components/chooseSelect';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import { useStore } from "vuex";
import pdaScan from '@/hooks/pdaScan.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import {ref,reactive,onMounted,watch,computed,toRaw} from 'vue';
import { submitHardwareWarehouseOut, scanHardwareBarcode } from '@/api/api.js'
import { onBackPress } from '@dcloudio/uni-app';
//JS国际化引入
import { useI18n } from 'vue-i18n';
components: {
	superweiCombox,
		chooseSelect,
		comboGrid
}
const { t } = useI18n();

let store = useStore();
//页面弹框输入数量使用的变量
let inputDialog = ref(null)
const { scan } = pdaScan()
let data = reactive({
	costItem: '',//费用项目
	remark: '',//备注
	userName: '',//领料人
	allInputNum: null,//总数量
	value: ['0'],
	wjOutScanList: [],//扫描存储数组
	warehouseName: '',// 仓库
	scanInfo: undefined, // 当前扫描信息
	locationCode: '',// 库位
	peportmentList: [],//领料人数组
	deportmentCode: '', //领料部code
	department: '', //领料部门
	scanValue: '',//扫码信息
	inputNum: null,//数量
	costItemValue:'',//费用项目
	requestParam: {
		code: 'ExpenseItem',
		value: ''
	},
	columnRule: {
		column: [{
			label: t('multilingual.coding'),
			name: "value",
		}, {
			label:t('taskList.expenseType'),
			name: "text",
		}]
	},
});
onMounted(() => {
	// 获取库位
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getInitData()
	// costItem()
})
const getInitData = async () => {
	// 获取领料人数据
	await getDataDictionaryFn('Deportment').then(res=>{
		data.peportmentList = res.data
	})
	
	let tepSelect1 = pitchOnFn(data.peportmentList)
	if (tepSelect1.length == 0) return
	data.department = tepSelect1[0].text // 默认选中第一个 text
	data.deportmentCode = tepSelect1[0].value  // 默认选中第一个 value
}

// 监听手动赋值
const computeData = () => {
	data.allInputNum = null
	if (!data.scanInfo && data.wjOutScanList.length > 0) {
		data.scanInfo = data.wjOutScanList[0]
	}
	if (data.scanInfo && data.wjOutScanList.length == 0) {
		data.scanInfo = undefined
		data.inputNum = null
	}
	data.wjOutScanList.forEach(element => {
		data.allInputNum += Number(element.inputNum)
	});
}
data.wjOutScanList = computed(() => {
	return store.state.hardWare.wjOutScanList
})
// 监听returnSpScanList变化
watch(() => data.wjOutScanList, () => {
	computeData()
}, {
	immediate: true,
	deep: true
});
//监听当前扫描信息的变化
watch(() => data.scanInfo, (newVal) => {
	if (!newVal) {
		data.warehouseName = ''
		data.locationCode = ''
		data.inputNum = null
	} else {
		data.warehouseName = newVal.warehouseName
		data.locationCode = newVal.locationCode
	}
}, {
	immediate: true,
	deep: true
});
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let arr = data.wjOutScanList.filter(x => x.barcode == code)
	if (arr.length > 0) {
		uni.showToast({ title: t('JsInternational.repeatTo'), icon: "none" });
		return
	}
	// if (!data.userName.length) {
	// 	uni.showToast({ title: t('materials.requisitionPerson'), icon: "none" });
	// 	return
	// }
	data.scanValue = code
	let parmes = {
		barcode: code,
	}
	scanHardwareBarcode(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '五金仓出库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.code == 0) {
			data.scanInfo = res.data
			data.scanInfo.inputNum = null
			// data.scanInfo.picker = data.userName
			data.scanInfo.remark = data.remark,
				data.scanInfo.costItem = data.costItem
				// data.scanInfo.costItemValue = data.costItemValue
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}
const chooseSelectItem = (e) => {
	data.userName = e.userName
}
const chooseSelectCostItem = (e) => {
	data.costItem = e.text
	data.costItemValue = e.value
}
// 弹框的取消按钮
const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close()
}
//弹框的确定按钮
const confirmFn = () => {
	if (data.scanInfo.inputNum == null) {
		// t('JsInternational.plsReturn')
		uni.showToast({ title: t('materials.pleaseEnterThe'), icon: "none" });
		return
	}
	if (data.scanInfo.inputNum > data.scanInfo.currentQty) {
		// t('JsInternational.plsReturn')
		uni.showToast({ title:t('materials.understock'), icon: "none" });
		data.scanInfo.inputNum = null
		return
	}
	// t('JsInternational.qtyCant')
	if (Number(data.scanInfo.inputNum) <= 0) {
		uni.showToast({ title: t('materials.outgoingQuantityCannot'), icon: "none" });
		return
	}
	store.dispatch('hardWare/setWjOutScanList', data.scanInfo)
	uni.showToast({ title: t('JsInternational.dataSaved'), icon: "none" });
	inputDialog.value.close();
}


const departmentSelect = (e) => {
	data.deportmentCode = e.value
}
//确定按钮
const handelSubmit = () => {
	if (data.wjOutScanList.length == 0) {
		uni.showToast({ title: t('JsInternational.scanInput'), icon: "none" });
		return
	}
	if (data.department.length == 0) {
		uni.showToast({ title: t('JsInternational.chooseDept'), icon: "none" });
		return
	}
	let tepData = toRaw(data.wjOutScanList)
	let wmsBarcodeList = []
	let remarkArr = []
	let pickerArr = []
	let costItemArr = []
	let costItemValueArr=[]
	tepData.forEach(x => {
		console.log(x, '-----wmsBarcodeList-----')
		wmsBarcodeList.push({
			id: x.id,
			outQty: x.inputNum,
			barcode:x.barcode
		})
		if (x.remark.length) {
			remarkArr.push(x.remark)
		}
		if (x.costItem.length) {
			costItemArr.push(x.costItem)
		}
		// if (x.costItemValue.length) {
		// 	costItemValueArr.push(x.costItemValue)
		// }
		pickerArr.push(x.picker)

	});
	let parmes = {
		deptCode: data.deportmentCode,
		lstBarcodeItem: wmsBarcodeList,
		picker: pickerArr.join(','),
		remarks: remarkArr.join(','),
		costItem: costItemValueArr.join(','),
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	submitHardwareWarehouseOut(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '五金仓出库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = null
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.dispatch('hardWare/resetWjOutScanList')
			data.scanInfo = null
			data.scanValue = null
			data.allInputNum = null
			data.userName = ''
			data.remark = ''
			data.costItem = ''
			// navigateBack()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.wjOutScanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return  true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					store.dispatch('hardWare/resetWjOutScanList')
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.wjOutScanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('hardWare/resetWjOutScanList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/hardware/hardwareDeliveryRecord'
	})
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0rpx;
	bottom: 0rpx;
	width: 100%
}

.item-info-title {
	width: 100px !important;
}
</style>
